package com.zzwcode.springweb.web.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import java.util.Date;
import java.util.Map;

@Controller
public class ErrorWebController implements ErrorController {

    private final ErrorAttributes errorAttributes;

    private static final Logger logger = LoggerFactory.getLogger(ErrorWebController.class);

    private static final String PREFIX = "";

    public ErrorWebController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }



    @RequestMapping("/error")
    public String error(HttpServletRequest httpServletRequest,WebRequest webRequest) {
        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(webRequest, ErrorAttributeOptions.defaults());
        String statusCode = StrUtil.toString(errorAttributes.get("status"));
        String clientRequestTime = DateUtil.format(new Date(), "yyyy年MM月dd日 HH:mm:ss");
        String clientRequestIP = httpServletRequest.getRemoteAddr();
        String clientRequestUrl = StrUtil.toString(errorAttributes.get("path"));
        String loggerTemplate = "[{}] IP：{} 访问路径\"{}\"发生异常! ";
        logger.error(StrUtil.format(loggerTemplate, clientRequestTime, clientRequestIP, clientRequestUrl));
        if (statusCode != null){
            int code = Integer.parseInt(statusCode.toString());
            if (code == HttpStatus.NOT_FOUND.value()){
                return "404";
            }
        }
        return "error";
    }
}
